package com.ltcode.auth.infrastructure.repository.impl;

import cn.hutool.json.JSONUtil;
import com.ltcode.auth.domain.model.AuthUser;
import com.ltcode.auth.domain.repository.AuthUserRepository;
import com.ltcode.auth.infrastructure.converter.AuthUserConverter;
import com.ltcode.auth.infrastructure.remote.feign.model.LoginUser;
import com.ltcode.auth.infrastructure.remote.feign.model.SysUserDTO;
import com.ltcode.auth.infrastructure.remote.feign.model.SysUserDomain;
import com.ltcode.auth.infrastructure.remote.feign.service.SysUserFeignService;
import com.ltcode.common.base.exception.BizException;
import com.ltcode.common.base.web.domain.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

/**
 * 认证用户仓储实现
 * 
 * @author ltcode
 * @since 2024-01-01
 */
@Slf4j
@Repository
@RequiredArgsConstructor
public class AuthUserRepositoryImpl implements AuthUserRepository {

    private final SysUserFeignService sysUserFeignService;

    @Override
    public Optional<AuthUser> findByUsername(String username) {
        try {
            ApiResponse<LoginUser> response = sysUserFeignService.getUserInfo(username);
            if (response.isSuccess() && response.getData() != null) {
                LoginUser data = response.getData();
                SysUserDomain userDomain = data.getSysUser();
                AuthUser authUser = AuthUserConverter.fromSysUserDomain(userDomain);
                // 设置权限和角色
                if (data.getPermissions() != null) {
                    authUser.setPermissions(data.getPermissions());
                }
                if (data.getRoles() != null) {
                    authUser.setRoles(data.getRoles());
                }
                
                return Optional.of(authUser);
            }
        } catch (Exception e) {
            log.error("根据用户名查询用户失败: {}", username, e);
        }
        return Optional.empty();
    }

    @Override
    public Optional<AuthUser> findById(Long userId) {
        try {
            ApiResponse<String> response = sysUserFeignService.getUserInfo(userId);
            if (response.isSuccess() && response.getData() != null) {
               String data = response.getData();
                SysUserDomain userDomain = JSONUtil.toBean(data, SysUserDomain.class);
                AuthUser authUser = AuthUserConverter.fromSysUserDomain(userDomain);
                return Optional.of(authUser);
            }
        } catch (Exception e) {
            log.error("根据用户ID查询用户失败: {}", userId, e);
        }
        return Optional.empty();
    }

    @Override
    public Optional<AuthUser> findByEmail(String email) {
        try {
            // 暂时通过用户名查询，实际应该调用专门的邮箱查询接口
            log.warn("根据邮箱查询用户功能暂未实现: {}", email);
            return Optional.empty();
        } catch (Exception e) {
            log.error("根据邮箱查询用户失败: {}", email, e);
        }
        return Optional.empty();
    }

    @Override
    public Optional<AuthUser> findByPhoneNumber(String phoneNumber) {
        try {
            // 暂时通过用户名查询，实际应该调用专门的手机号查询接口
            log.warn("根据手机号查询用户功能暂未实现: {}", phoneNumber);
            return Optional.empty();
        } catch (Exception e) {
            log.error("根据手机号查询用户失败: {}", phoneNumber, e);
        }
        return Optional.empty();
    }

    @Override
    public AuthUser save(AuthUser user) {
        SysUserDTO userDTO = AuthUserConverter.toSysUserDTO(user);
        ApiResponse<Boolean> response = sysUserFeignService.registerUser(userDTO);
        if (!response.isSuccess()) {
            throw new BizException("保存用户失败: " + response.getMsg());

        }
        return user;
    }

    @Override
    public void updateLoginInfo(Long userId, String loginIp) {
        try {
            log.warn("更新用户登录信息功能暂未实现: userId={}, loginIp={}", userId, loginIp);
        } catch (Exception e) {
            log.error("更新用户登录信息失败: userId={}, loginIp={}", userId, loginIp, e);
        }
    }

    @Override
    public void updatePassword(Long userId, String newPassword) {
        try {
            log.warn("更新用户密码功能暂未实现: userId={}", userId);
        } catch (Exception e) {
            log.error("更新用户密码失败: userId={}", userId, e);
            throw new RuntimeException("更新用户密码失败", e);
        }
    }

    @Override
    public boolean existsByUsername(String username) {
        ApiResponse<LoginUser> userInfo = sysUserFeignService.getUserInfo(username);
        if (!userInfo.isSuccess()) {
            throw new BizException("内部服务异常");
        }
        LoginUser data = userInfo.getData();
        SysUserDomain sysUser = data.getSysUser();
        return sysUser != null;
    }

    @Override
    public boolean existsByEmail(String email) {
        ApiResponse<LoginUser> userInfo = sysUserFeignService.getUserInfoByEmail(email);
        if (!userInfo.isSuccess()) {
            throw new BizException("内部服务异常");
        }
        LoginUser data = userInfo.getData();
        SysUserDomain sysUser = data.getSysUser();
        return sysUser != null;
    }

    @Override
    public boolean existsByPhoneNumber(String phoneNumber) {
        ApiResponse<LoginUser> userInfo = sysUserFeignService.getUserInfoByPhone(phoneNumber);
        if (!userInfo.isSuccess()) {
            throw new BizException("内部服务异常");
        }
        LoginUser data = userInfo.getData();
        SysUserDomain sysUser = data.getSysUser();
        return sysUser != null;
    }

    @Override
    public Set<String> findPermissionsByUserId(Long userId) {
        try {
            // 临时返回一些默认权限，实际应该调用权限查询接口
            log.info("获取用户权限: userId={}", userId);
            Set<String> permissions = new HashSet<>();
            permissions.add("system:user:list");
            permissions.add("system:user:query");
            permissions.add("system:role:list");
            permissions.add("system:role:query");
            permissions.add("system:menu:list");
            permissions.add("system:menu:query");
            permissions.add("system:dict:list");
            permissions.add("system:dict:query");
            permissions.add("monitor:operlog:list");
            permissions.add("monitor:logininfor:list");
            permissions.add("monitor:online:list");
            permissions.add("monitor:job:list");
            permissions.add("tool:build:view");
            permissions.add("tool:gen:list");
            permissions.add("tool:swagger:view");
            return permissions;
        } catch (Exception e) {
            log.error("获取用户权限失败: userId={}", userId, e);
        }
        return new HashSet<>();
    }

    @Override
    public Set<String> findRolesByUserId(Long userId) {
        try {
            // 临时返回一些默认角色，实际应该调用角色查询接口
            log.info("获取用户角色: userId={}", userId);
            Set<String> roles = new HashSet<>();
            roles.add("admin");
            roles.add("common");
            return roles;
        } catch (Exception e) {
            log.error("获取用户角色失败: userId={}", userId, e);
        }
        return new HashSet<>();
    }
}
